package net.entelijan.config.impl2;

import java.util.List;

import javax.swing.AbstractButton;
import javax.swing.JTable;
import javax.swing.text.JTextComponent;

import net.entelijan.cobean.bind.impl.BoundPropBinding;
import net.entelijan.cobean.core.ColumnDesc;
import net.entelijan.cobean.core.ICobean;
import net.entelijan.cobean.table.DefaultSingleSelectionTableInitializer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DefaultTableInitializerBinderFactory extends AbstractBinderFactory {

	private Log log = LogFactory
			.getLog(DefaultTableInitializerBinderFactory.class);

	public DefaultTableInitializerBinderFactory() {
		super();
	}

	@Override
	protected List<List<String>> adjustPathesOfCoreComponent(
			List<List<String>> pathes) {
		return PathUtil.getHeads(pathes, "table");
	}

	@Override
	protected boolean isCoreComponent(IEnhancedComponent comp) {
		return comp.getComponent() instanceof JTable
				&& (PathUtil.containsAnyKeywordIgnoreCase(comp.getPathes(),
						"table"));
	}

	@SuppressWarnings("unchecked")
	@Override
	protected ICobean<?> createCobean(IEnhancedComponent coreComp,
			List<IEnhancedComponent> allComps, Class<?> modelPropertyType,
			Object config) {
		JTable core = (JTable) coreComp.getComponent();
		JTextComponent filterInput = findComponent(allComps, coreComp,
				JTextComponent.class, "filterInput");
		AbstractButton filterButton = findComponent(allComps, coreComp,
				AbstractButton.class, "filterButton");
		DefaultSingleSelectionTableInitializer<?> ini = new DefaultSingleSelectionTableInitializer();
		ini.setCoTable(core);
		ini.setCoFilterInput(filterInput);
		ini.setCoFilterButton(filterButton);
		if (config == null) {
			throw new IllegalArgumentException("Config must not be 'null'");
		}
		if (!(config instanceof List)) {
			throw new IllegalArgumentException("Config '" + config
					+ "' must not be a List of ColumnDesc");
		}
		for (Object obj : (List<Object>) config) {
			if (!(obj instanceof ColumnDesc)) {
				throw new IllegalArgumentException("Config '" + config
						+ "' must not be a ColumnDesc");
			}
		}
		ini.setColumnDescs((List<ColumnDesc>) config);
		return ini.initialize();
	}

	protected <T> T bindSelectedValue(T model, String modelPath,
			ICobean<?> cobean) {
		BoundPropBinding pbsel = new BoundPropBinding();
		pbsel.setCompProperty("selectedValue");
		pbsel.setModelPath(modelPath);
		model = pbsel.bind(model, cobean);
		log.info("binding cobean with selected value '" + modelPath + "'");
		return model;

	}

}
